package com.zh.work.controller.platform.merch;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zh.common.entity.JSONResult;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zh.common.entity.Oauth;
//import com.zh.work.config.CustomerWebSocketHandler;
import com.zh.work.dao.platform.merch.MerchInfoMapper;
import com.zh.work.entity.merch.MerchInfoEntity;
import com.zh.work.entity.merch.QrCodeMerchFee;
import com.zh.work.service.platform.merch.MerchInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * @Description: 商户信息管理
 * @Author: Li.HuiNeng
 * @Create in: 2019/11/14
 * @Version: 1.0.1
 */
@Api(value = "商户信息管理控制器", produces = "application/json", tags = {"商户信息管理控制器"})
@RestController
@RequestMapping("/merchantInfo")
public class MerchInfoController {

    /**
     * @Description: 简易crud时使用
     * ------------------------
     * @Author: Li.HuiNeng
     * @Date: 2019/11/14
     */
    @Autowired
    private MerchInfoMapper mapper;

    /**
     * @Description: 有业务逻辑需要处理时使用
     * ------------------------
     * @Author: Li.HuiNeng
     * @Date: 2019/11/14
     */
    @Autowired
    private MerchInfoService service;

    /**
     * @Description: mongodb实例
     * ------------------------
     * @Author: Li.HuiNeng
     * @Date: 2020/5/27
     */
    @Autowired
    private MongoTemplate mongoTemplate;



    @ApiOperation(value = "新增一条记录", tags = {"putMerchantInfo"}, notes = "新增一条记录")
    @PutMapping("/putMerchantInfo")
    @ResponseBody
    public JSONResult<Object> putMerchantInfo(@ApiParam(value = "商户信息实体类", name = "merchInfoEntity") @RequestBody MerchInfoEntity merchInfoEntity) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        try {
            int i = this.service.putMerchantInfo(merchInfoEntity);
            jsonResult.setSuccess(false);
            switch (i) {
                case -1:
                    jsonResult.setMessage("新增商户,无法获取机构编号!");
                    break;
                case -2:
                    jsonResult.setMessage("新增商户,构造商户编号失败!");
                    break;
                case -3:
                    jsonResult.setMessage("新增商户,添加商户二维码失败!");
                    break;
                case -4:
                    jsonResult.setMessage("新增商户,新增商户信息主体失败!");
                    break;
                default:
                    jsonResult.setMessage("其他错误.");
            }
            if (i > 0) {
                jsonResult.setCode(200);
                jsonResult.setMessage("添加完成");
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setMessage("添加失败,请检查参数是否填写完整!");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setCode(e.hashCode());
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
            e.printStackTrace();
        }
        return jsonResult;
    }


    @ApiOperation(value = "通过id修改信息", tags = {"updateMerchantInfoById"}, notes = "通过id修改信息")
    @PutMapping("/updateMerchantInfoById")
    @ResponseBody
    public JSONResult<Object> updateMerchantInfoById(@ApiParam(value = "商户信息实体类", name = "merchInfoEntity") @RequestBody MerchInfoEntity merchInfoEntity) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        try {
            int i = this.service.modMerchantInfoById(merchInfoEntity);
            if (i > 0) {
                jsonResult.setCode(200);
                jsonResult.setMessage("修改完成");
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setMessage("修改失败,请检查参数是否填写完整!");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setCode(e.hashCode());
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setSuccess(false);
            e.printStackTrace();
        }
        return jsonResult;
    }

    @ApiOperation(value = "根据主键删除记录", tags = {"deleteMerchantInfoById"}, notes = "根据主键删除记录")
    @DeleteMapping("/deleteMerchantInfoById")
    public JSONResult<Object> deleteMerchantInfoById(@ApiParam(value = "商户信息实体类", name = "merchInfoEntity") MerchInfoEntity merchInfoEntity) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        try {
            if (merchInfoEntity.deleteById()) {
                jsonResult.setCode(200);
                jsonResult.setMessage("删除完成");
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setMessage("删除失败,请检查参数是否填写完整!");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setCode(e.hashCode());
            e.printStackTrace();
        }
        return jsonResult;
    }

    @ApiOperation(value = "根据主键列表批量删除记录", tags = {"deleteMerchantInfoBatchByIds"}, notes = "该传参时 请选择raw(application/json)格式传入")
    @DeleteMapping("/deleteMerchantInfoBatchByIds")
    @ResponseBody
    public JSONResult<Object> deleteMerchantInfoBatchByIds(@ApiParam(value = "主键集合", name = "ids") @RequestBody @RequestParam("ids") List<Integer> ids) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        try {
            int c = this.mapper.deleteBatchIds(ids);
            if (c > 0) {
                jsonResult.setCode(200);
                jsonResult.setMessage("删除完成");
                jsonResult.setSuccess(true);
            } else {
                jsonResult.setMessage("删除失败,请检查参数是否填写完整!");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setCode(e.hashCode());
            e.printStackTrace();
        }
        return jsonResult;
    }

    @ApiOperation(value = "根据id查询详细信息", tags = {"getMerchantInfoById"}, notes = "根据id查询详细信息")
    @GetMapping("/getMerchantInfoById")
    public JSONResult<MerchInfoEntity> getMerchantInfoById(@ApiParam(value = "商户信息实体类", name = "MerchInfo") MerchInfoEntity merchInfoEntity) {
        JSONResult<MerchInfoEntity> jsonResult = new JSONResult<>();
        try {
            MerchInfoEntity result = (MerchInfoEntity) merchInfoEntity.selectById(merchInfoEntity.getId());
            if (result != null) {
                jsonResult.setCode(200);
                jsonResult.setMessage("查询完成");
                jsonResult.setSuccess(true);
                jsonResult.setData(result);
            } else {
                jsonResult.setMessage("未查询到相应信息，请检查参数是否正确");
                jsonResult.setSuccess(false);
            }
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setCode(e.hashCode());
            e.printStackTrace();
        }
        return jsonResult;
    }


    @ApiOperation(value = "分页查询参数数据集", tags = {"getPagesMerchInfos"}, notes = "分页查询参数数据集")
    @GetMapping("/getPagesMerchantInfos")
    public JSONResult<List<MerchInfoEntity>> getPagesMerchantInfos(
            @ApiParam(value = "起始页", name = "pageNo") Integer pageNo,
            @ApiParam(value = "当前页显示数量", name = "pageNo") Integer pageSize,
            @ApiParam(value = "商户信息实体类", name = "merchInfoEntity") MerchInfoEntity merchInfoEntity) {
        JSONResult<List<MerchInfoEntity>> jsonResult = new JSONResult<>();
        try {
            Page<MerchInfoEntity> page = new Page<>(pageNo, pageSize);
            IPage<MerchInfoEntity> result = this.service.getMerchantPage(page, merchInfoEntity);
            jsonResult.setTotal(page.getTotal());
            jsonResult.setData(result.getRecords());
            jsonResult.setMessage("操作成功");
            jsonResult.setSuccess(true);
            jsonResult.setCode(200);
        } catch (Exception e) {
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setSuccess(false);
            e.printStackTrace();
        }
        return jsonResult;
    }


    @ApiOperation(value = "分页查询商户指定数据", tags = {"getPagesMerchantAssigeInfos"}, notes = "分页查询商户指定数据")
    @GetMapping("/getPagesMerchantAssigeInfos")
    public JSONResult<List<Map<String, Object>>> getPagesMerchantAssigeInfos(@RequestParam(value = "json") String json) {
        JSONResult<List<Map<String, Object>>> jsonResult = new JSONResult<>();
        try {
            String name = "";
            String agentNo = "";
            Map<String, String> map = (Map) JSON.parse(json);
            if (map != null) {
                name = map.get("name");
                agentNo = map.get("agentNo");
            }
            List<Map<String, Object>> list = mapper.selectMaps(new LambdaQueryWrapper<MerchInfoEntity>()
                    .select(MerchInfoEntity::getMerchNo, MerchInfoEntity::getMerchName)
                    .like(StringUtils.isNotEmpty(name), MerchInfoEntity::getMerchName, name)
                    .eq(StringUtils.isNotEmpty(agentNo), MerchInfoEntity::getSuperAgent, agentNo)
                    .last("limit 50")
            );
            jsonResult.setData(list);
            jsonResult.setMessage("操作成功");
            jsonResult.setSuccess(true);
            jsonResult.setCode(200);
        } catch (Exception e) {
            jsonResult.setMessage(e.getLocalizedMessage());
            jsonResult.setSuccess(false);
            e.printStackTrace();
        }
        return jsonResult;
    }


    @ApiOperation(value = "商户审核", tags = {"putMerchantAudit"}, notes = "商户审核")
    @PutMapping("/putMerchantAudit")
    public JSONResult<Object> putMerchantAudit(@ApiParam(value = "商户信息实体类", name = "merchInfoEntity") MerchInfoEntity merchInfoEntity) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        try {
            int i = this.service.putMerchantAudit(merchInfoEntity);
            if (i > 0)
                jsonResult.setSuccess(true);
            else {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("商户审核出现错误!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }

    @ApiOperation(value = "查询指定商户上级代理费率信息", tags = {"getMerchParentAgent"}, notes = "查询指定商户上级代理费率信息")
    @GetMapping("/getMerchParentAgent")
    public JSONResult<Object> getMerchParentAgent(@ApiParam(value = "商户信息实体类", name = "merchInfoEntity") MerchInfoEntity merchInfoEntity) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        try {
            int i = this.service.putMerchantAudit(merchInfoEntity);
            if (i > 0)
                jsonResult.setSuccess(true);
            else {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("商户审核出现错误!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }

    @ApiOperation(value = "查询指定商户二维码费率信息", tags = {"getMerchantQrCodeFee"}, notes = "查询指定商户二维码费率信息")
    @GetMapping("/getMerchantQrCodeFee")
    public JSONResult<Object> getMerchantQrCodeFee(@ApiParam(value = "商户编号", name = "merchantNo")
                                                   @RequestParam(value = "merchantNo", required = false) String merchantNo) {
        JSONResult<Object> jsonResult = new JSONResult<>();
        try {
            List<QrCodeMerchFee> list = this.service.getMerchantQrCodeFee(merchantNo);
            if (list.size() > 0) {
                jsonResult.setSuccess(true);
                jsonResult.setData(list);
            } else {
                jsonResult.setSuccess(false);
                jsonResult.setMessage("编号为【" + merchantNo + "】商户二维码费率为空!默认设置为上级平台费率");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }

    @ApiOperation(value = "根据商户编号获取商户列表信息", tags = {"getMerchantListIsNo"}, notes = "根据商户编号获取商户列表信息")
    @GetMapping("/getMerchantListIsNo")
    public JSONResult<List<MerchInfoEntity>> getMerchantListIsNo(@ApiParam(value = "商户编号", name = "merchantNo")
                                                                 @RequestParam(required = false, value = "merchantNo") String merchantNo) {
        JSONResult<List<MerchInfoEntity>> jsonResult = new JSONResult<>();
        try {
            List<MerchInfoEntity> list = mapper.selectList(new LambdaQueryWrapper<MerchInfoEntity>()
                    .eq(StringUtils.isNotEmpty(merchantNo), MerchInfoEntity::getMerchNo, merchantNo));
            jsonResult.setData(list);
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }

    @ApiOperation(value = "查询指定商户列表信息", tags = {"getMerchantInfos"}, notes = "查询指定商户列表信息")
    @GetMapping("/getMerchantInfos")
    public JSONResult<List<MerchInfoEntity>> getMerchantInfos() {
        JSONResult<List<MerchInfoEntity>> jsonResult = new JSONResult<>();
        try {
            List<MerchInfoEntity> list = mapper.selectList(new LambdaQueryWrapper<MerchInfoEntity>()
                    .select(MerchInfoEntity::getId, MerchInfoEntity::getMerchNo, MerchInfoEntity::getMerchName)
            );
            jsonResult.setData(list);
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
        }
        return jsonResult;
    }

    @ApiOperation(value = "获取指定代理商下的商户列表信息", tags = {"getMerchListByAgentNo"}, notes = "获取指定代理商下的商户列表信息")
    @GetMapping("/getMerchListByAgentNo")
    public JSONResult<List<MerchInfoEntity>> getMerchListByAgentNo(@ApiParam(value = "代理商编号编号", name = "agentNo")
                                                                   @RequestParam(value = "agentNo", required = false) String agentNo) {
        JSONResult<List<MerchInfoEntity>> jsonResult = new JSONResult<>();
        try {
            List<MerchInfoEntity> list = this.service.getMerchListByAgentNo(agentNo);
            jsonResult.setData(list);
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            jsonResult.setData(null);
            jsonResult.setSuccess(false);
            jsonResult.setMessage("获取指定机构下的代理商列表信息失败!" + e.getLocalizedMessage());
            e.printStackTrace();
        }
        return jsonResult;
    }



    @ApiOperation(value = "通过用户查询绑定的外键信息", tags = {"getMerchInfoByUserId"}, notes = "通过用户查询绑定的外键信息")
    @GetMapping("/getMerchInfoByUserId")
    public JSONResult<Object> getMerchInfoByUserId() {
        JSONResult<Object> jsonResult = new JSONResult<>();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Oauth auth = (Oauth) authentication.getPrincipal();
        Map<String,String> map = new HashMap<>();
        try {
            map = service.getMerchInfoByUserId(auth.getId());
            jsonResult.setData(map);
            jsonResult.setSuccess(true);
        } catch (Exception e) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage(e.getLocalizedMessage());
            e.printStackTrace();
        }
        return jsonResult;
    }





}
